package cn.source.web.controller.zk;

import cn.source.common.core.controller.BaseController;
import cn.source.common.core.domain.AjaxResult;
import cn.source.common.core.domain.entity.SysRole;
import cn.source.common.core.domain.entity.SysUser;
import cn.source.common.core.page.TableDataInfo;
import cn.source.common.utils.SecurityUtils;
import cn.source.common.utils.poi.ExcelUtil;
import cn.source.framework.web.domain.server.Sys;
import cn.source.system.service.ISysRoleService;
import cn.source.system.service.ISysUserService;
import cn.source.zk.domain.entity.*;
import cn.source.zk.domain.vo.DeviceChannelVO;
import cn.source.zk.domain.vo.DeviceSortVO;
import cn.source.zk.mapper.ZkSubstationMapper;
import cn.source.zk.service.IZkAreaService;
import cn.source.zk.service.IZkChannelService;
import cn.source.zk.service.IZkDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/zk/device")
@Slf4j
public class ZkDeviceController extends BaseController {

    @Autowired
    private IZkDeviceService deviceService;

    @Autowired
    private IZkChannelService channelService;

    @Autowired
    private ZkSubstationMapper substationMapper;

    @Autowired
    private IZkAreaService areaService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService userService;


    /**
     * 获取设备主表分页列表
     *
     * @param device
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo listPage(Device device) {
        startPage();

        List<Device> list = deviceService.listPage(device);

        return getDataTable(list);
    }

    @GetMapping("/device/stats")
    public AjaxResult getDeviceStats() {
        Map<String, Object> stats = deviceService.getDeviceStats();
        return AjaxResult.success(stats);
    }

    @GetMapping("/listFold")
    public TableDataInfo listPageFold(Device device) {
        // 设置地区的所有子级id
        List<Long> child = areaService.getChild(device.getAreaNum());
        device.setAreaChildNums(child);
//        根据用户权限展示相应的数据
        List<SysRole> sysRoles = roleService.selectRolesListByUserId(SecurityUtils.getUserId());
        if (sysRoles.size() > 0) {
            SysRole sysRole = sysRoles.get(0);
            // 一级管理员
            if (sysRole.getRoleKey().equals("company")) {
                SysUser sysUserQueryParams = new SysUser();
                sysUserQueryParams.setCreateBy(SecurityUtils.getUsername());
                List<SysUser> sysUsers = userService.selectUserList(sysUserQueryParams);
                String createByStr = SecurityUtils.getUsername();
                if (sysUsers.size() > 0) {
                    String bufferStr = sysUsers.stream().map(m -> m.getUserName()).collect(Collectors.joining(","));
                    createByStr = createByStr + ',' + bufferStr;
                }
                device.setCreateBy(createByStr);
            }
            // 普通管理员
            if (sysRole.getRoleKey().equals("common")) {
                device.setCreateBy(SecurityUtils.getUsername());
            }

            // 一般人员
            if (sysRole.getRoleKey().equals("general")) {
                device.setCreateBy(SecurityUtils.getUsername());
            }
        }


        //设置当前用户
        Substation substation = new Substation();
        substation.setCompanyId(SecurityUtils.getCompanyId());
        List<Substation> substationsList = substationMapper.selectListPage(substation);
        List<Long> substationsNumList = substationsList.stream().map(Substation::getNum).collect(Collectors.toList());
        startPage();
        List<DeviceChannelVO> list = deviceService.listPageFold(device, substationsNumList);

        return getDataTable(list);
    }

    @GetMapping("/getDeviceByNotAuth")
    public TableDataInfo getDeviceByNotAuth(Device device) {
        startPage();
        List<Device> list = deviceService.selectDeviceByNotAuth(device);
        return getDataTable(list);
    }

    @PostMapping()
    public AjaxResult add(@RequestBody Device device) {

        //校验devNum不能相同
        List<Device> devices = deviceService.getByDevNum(device.getDevNum());
        if (!devices.isEmpty()) {
            return AjaxResult.error("设备编号已存在！");
        }
        return toAjax(deviceService.add(device));
    }

    /**
     * 根据num查询设备
     *
     * @param num
     * @return
     */
    @GetMapping("/{num}")
    public AjaxResult getByNum(@PathVariable Long num) {
        Device device = deviceService.getByNum(num);

        return AjaxResult.success(device);
    }

    /**
     * 修改设备
     *
     * @param device
     * @return
     */
    @PutMapping()
    public AjaxResult edit(@RequestBody Device device) {
        //设置创建者和修改人
        device.setUpdateBy(getUsername());

        return toAjax(deviceService.edit(device));
    }

    @DeleteMapping("/{nums}")
    public AjaxResult removeBatch(@PathVariable List<Long> nums) {

        // 判断设备下是否有通道
        List<Channel> channelList = channelService.getChannelByDeviceNums(nums);
        if (!channelList.isEmpty()) {
            return AjaxResult.error("设备下有通道，不允许删除！");
        }

        return toAjax(deviceService.removeBatch(nums));
    }

    @PostMapping("/export")
    public void export(HttpServletResponse response, Device device) {
        //设置当前用户
        Substation substation = new Substation();
        substation.setCompanyId(SecurityUtils.getCompanyId());
        List<Substation> substationsList = substationMapper.selectListPage(substation);
        List<Long> substationsNumList = substationsList.stream().map(Substation::getNum).collect(Collectors.toList());

        List<DeviceChannelVO> list = deviceService.listPageFold(device, substationsNumList);
        ExcelUtil<DeviceChannelVO> util = new ExcelUtil<DeviceChannelVO>(DeviceChannelVO.class);
        util.exportExcel(response, list, "设备信息");
    }

    /**
     * 获取已有的设备排序
     *
     * @return
     */
    @GetMapping("/getSortList")
    public AjaxResult getSortList() {
        List<DeviceSortVO> sortList = deviceService.getSortList();

        return AjaxResult.success(sortList);
    }

}
